package com.hxzy.three.controller; /**
 * @author wzm
 * @create 2023-09-20 15:26
 * project_name:javaweb2308
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hxzy.three.entity.User;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

//改良UserController  所有的功能都定义在该类中  而不是一个功能一个Servlet
@WebServlet("/user/*")  // /user/delete 匹配任意user下的路径
public class UserServlet01 extends BaseServlet{

    //新增用户
    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("新增");
    }
    //删除用户
    protected void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("删除");
    }
    //修改用户
    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    //查询单个
    protected void findById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    //查询全部
    protected void findByAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     //模拟响应JSON数据
        List<User> list = new ArrayList<>();
        //模拟查询数据库中所有的User
        for (int i = 1; i <= 10; i++){
            list.add(new User(i,"name"+i,"pwd"+i));
        }

        //将Java对象转为JSON字符串才能够响应到浏览器
        System.out.println("list = " + list);

        //Java->JSON字符串
//        String s = JSON.toJSONString(list);//list对象

        String s = JSON.toJSONString(new User(1,"王二狗","123456"));//user对象

        //JSON字符串->java对象
        JSON.parseObject(s, User.class);

        response.setContentType("text/json;charset=UTF-8");
        //response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(s);


    }


}
